package com.mhc.suzuki.controller;


import com.mhc.haval.security.model.User;
import com.mhc.suzuki.api.model.DataDictDTO;
import com.mhc.suzuki.api.service.IDataDictService;
import com.mhc.suzuki.constant.ErrorCodeEnum;
import com.mhc.suzuki.vo.DataDictVO;
import com.subaru.common.entity.BizResult;
import com.subaru.common.util.BeanCopierUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;

/**
 * Created by HW
 * on 2017/8/14 15:00.
 */
@Slf4j
@Controller
@RequestMapping(value = "/dataDict")
public class DataDictController {


    @Autowired
    private IDataDictService iDataDictService;


    /**
     * 获取某分组下元数据
     * @param dataGroupCode url变量，分组code
     * @param user 登录用户
     * @return
     */
    @ApiOperation(value = "获取某分组下元数据", notes = "点击分组列表某行，显示该分组下的元数据")
    @ApiImplicitParam(name = "dataGroupCode", value = "分组名称", paramType = "path", required = true, dataType = "String")
    @RequestMapping(value = "/{dataGroupCode}", method = RequestMethod.GET)
    public @ResponseBody
    BizResult<List<DataDictVO>> getGroupData(@PathVariable String dataGroupCode, @AuthenticationPrincipal User user) {
        Optional<User> userOptional = Optional.ofNullable(user);
        if (userOptional.isPresent()) {
            //获取公司编号
            String companyNo = user.getCompanyNo();

            List<DataDictDTO> dataDictDTOS = iDataDictService.getGroupDataList(dataGroupCode, companyNo);
            List<DataDictVO> dataDictVOS = copyDOListToVOLIst(dataDictDTOS);
            return BizResult.create(dataDictVOS, true, ErrorCodeEnum.SUCCESS.getErrCode(), ErrorCodeEnum.SUCCESS.getErrMsg());

        } else {
            return BizResult.create(ErrorCodeEnum.NOT_LOGIN.getErrCode(), ErrorCodeEnum.NOT_LOGIN.getErrMsg());
        }

    }



    /**
     * DataDictDOList转为DataDictVOLIst
     * @param dataDictDTOS
     * @return
     */
    private List<DataDictVO> copyDOListToVOLIst(List<DataDictDTO> dataDictDTOS) {
        List<DataDictVO> dataDictVOS = new ArrayList<>();
        Iterator<DataDictDTO> iterator = dataDictDTOS.iterator();
        while(iterator.hasNext()){
            DataDictDTO dataDictDTO = iterator.next();
            DataDictVO dataDictVO = BeanCopierUtil.convert(dataDictDTO, DataDictVO.class);
            dataDictVOS.add(dataDictVO);
        }
        return dataDictVOS;
    }

}
